# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, redirect, HttpResponse
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from app_WebChat import forms
import Queue
import json
import time

GLOBAL_MSG_QUEUES = {

}

def index(request):
	context = {}
	context['is_login'] = request.session.get('IS_LOGIN', False)
	return render(request, 'index.html', context)

# 注册
def register(request):
	context = {}
	if request.method == 'POST':
		form = forms.UserForm(request.POST)
		context['form'] = form
		if form.is_valid():
			# 获得表单数据
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']
			password2 = request.POST.get('password2', None)

			# 判断用户是否存在
			user = auth.authenticate(username=username, password=password)
			if user is not None:
				request.session['IS_LOGIN'] = False
				context['err_msg'] = '<{}>该用户已注册'.format(username)
				return render(request, 'register.html', context)
			elif password != password2:
				request.session['IS_LOGIN'] = False
				context['err_msg'] = '两次输入的密码不一致'
				return render(request, 'register.html', context)
			else:
				# 添加到数据库
				user = User.objects.create_user(username=username, password=password)
				user.save()
				# 添加到session
				request.session['IS_LOGIN'] = True
				request.session['username'] = username
				# 调用auth登录
				auth.login(request, user)
				# 重定向到首页
				return redirect('/')
		else:
			request.session['IS_LOGIN'] = False
			context['errors'] = form.errors
			return render(request, 'register.html', context)
	else:
		form = forms.UserForm()
		context['form'] = form
		request.session['IS_LOGIN'] = False
	return render(request, 'register.html', context)


# 登陆
def login(request):
	context = {}
	if request.method == 'POST':
		form = forms.UserForm(request.POST)
		context['form'] = form
		if form.is_valid():
			# 获取表单用户密码
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']

			# 获取的表单数据与数据库进行比较
			user = authenticate(username=username, password=password)
			if user is not None and user.is_active:
				# 比较成功，跳转index
				auth.login(request, user)
				request.session['IS_LOGIN'] = True
				request.session['username'] = username
				return redirect('/')
			else:
				# 比较失败，停留login
				request.session['IS_LOGIN'] = False
				context['err_msg'] = '用户名或密码错误'
				return render(request, 'login.html', context)
		else:
			request.session['IS_LOGIN'] = False
			context['errors'] = form.errors
			return render(request, 'login.html', context)
	else:
		form = forms.UserForm()
		context['form'] = form
		request.session['IS_LOGIN'] = False
	return render(request, 'login.html', context)


# 登出
def logout(request):
	# 清理cookie里保存username
	auth.logout(request)
	# request.session.flush()  # 也可以清理cookie
	return redirect('/')


def setpwd(request):
	context = {}
	if request.method == 'POST':
		username = request.POST.get('username', None)
		password = request.POST.get('password', None)
		password2 = request.POST.get('password2', None)

		user = auth.authenticate(username=username, password=password)
		if user is None:
			context['err_msg'] = '用户名或密码不正确'
			return render(request, 'setpwd.html', context)
		else:
			user.set_password(password2)
			user.save()
			request.session['IS_LOGIN'] = True
			request.session['username'] = username
			return redirect('/')
	else:
		pass
	return render(request, 'setpwd.html', context)


@login_required
def chat_room(request):
	return render(request, 'chat_room.html')


@login_required
def send_msg(request):
	print request.user.userprofile.name
	print request.POST
	print request.POST.get('msg',None)

	# if request.POST.get()

	msg_data = request.POST.get('data')
	if msg_data:
		msg_data = json.loads(msg_data)
		msg_data['timestamp'] = time.time()
		if msg_data['type'] == 'single':
			if not GLOBAL_MSG_QUEUES.get(int(msg_data['to'])):
				GLOBAL_MSG_QUEUES[int(msg_data['to'])] = Queue.Queue()
			GLOBAL_MSG_QUEUES[int(msg_data['to'])].put(msg_data)
	print GLOBAL_MSG_QUEUES
	return HttpResponse('---MSG RECEVIESD---')


def get_new_msgs(request):

	if request.user.userprofile.id not in GLOBAL_MSG_QUEUES:
		print ('no Queue for user [{}]'.format(request.user.userprofile.id), request.user)
		GLOBAL_MSG_QUEUES[request.user.userprofile.id] = Queue.Queue()
	msg_count = GLOBAL_MSG_QUEUES[request.user.userprofile.id].qsize()
	q_obj = GLOBAL_MSG_QUEUES[request.user.userprofile.id]
	msg_list = []
	if msg_count > 0:
		for msg in range(msg_count):
			msg_list.append(q_obj.get())
		print ('new msgs:', msg_list)
		return HttpResponse(json.dumps(msg_list))
	else:  # 无消息时，挂起
		# print ('没有消息', request.user, request.user.userprofile.id)
		# print GLOBAL_MSG_QUEUES
		try:
			msg_list.append(q_obj.get(timeout=60))
		except Queue.Empty:
			print '\033[41;1mno msg for [{}][{}], timeout\033[0m'.format(request.user.userprofile.id, request.user)
		return HttpResponse(json.dumps(msg_list))
